/*
 * SteepTimer - A timer designed for tea fanatics
 * Copyright (C) 2011  Wesley Crossman
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "TeaAlarmDialog.h"
#include "TeaSound.h"
#include "ui_TeaAlarmDialog.h"
#include <QDebug>
#include <QTimer>
#include <QSettings>
/*#ifdef Q_OS_WIN
#include <qt_windows.h>
#endif*/

TeaAlarmDialog::TeaAlarmDialog(int nextIndex, QWidget *parent) :
            QDialog(parent, Qt::Dialog|Qt::WindowStaysOnTopHint|Qt::MSWindowsFixedSizeDialogHint),
            m_ui(new Ui::TeaAlarmDialog),
            m_return(Close),
            m_sounded(0) {
    m_soundTimer = new QTimer(this);
    m_soundTimer->setSingleShot(true);
    connect( m_soundTimer, SIGNAL(timeout()), TeaSound::instance(), SLOT(play()) );

    m_lateTimer = new QTimer(this);
    m_lateTimer->start(1000);
    connect( m_lateTimer, SIGNAL(timeout()), SLOT(lateTimeout()) );
    m_elapsed.start();

    connect( TeaSound::instance(), SIGNAL(aboutToFinish()), SLOT(soundAboutToFinish()) );
    m_ui->setupUi(this);
    if (nextIndex == 0) {
        m_ui->btnStartNext->setText(tr("&Start Over"));
    }
    m_mediaObject = NULL;
    QTimer::singleShot(50, this, SLOT(lazyLoad()));
/*#ifdef Q_OS_WIN
    MessageBeep(MB_ICONINFORMATION);
#endif*/
}

TeaAlarmDialog::~TeaAlarmDialog() {
    TeaSound::instance()->stop();
    delete m_ui; m_ui = NULL;
}

void TeaAlarmDialog::lazyLoad() {
    TeaSound::instance()->play();
}

void TeaAlarmDialog::on_btnStartNext_clicked() {
    m_return = StartNext;
    accept();
}

void TeaAlarmDialog::lateTimeout() {
    int secs = m_elapsed.elapsed()/1000;
    if (secs > 10) {
        if (secs < 60) {
            m_ui->lblTimeElapsed->setText(tr("%1 seconds late").arg(secs));
        } else {
            m_ui->lblTimeElapsed->setText(tr("%1:%2 late")
                    .arg(secs/60)
                    .arg(secs%60, 2, 10, QChar('0')));
        }
    }
}

void TeaAlarmDialog::soundAboutToFinish() {
    QSettings settings;
    ++m_sounded;
    int repeat = settings.value("settings/soundRepeat").toInt();
    bool delay = settings.value("settings/soundDelay").toBool();
    if (repeat+1 > m_sounded || repeat == -1) {
        if (delay) {
            m_soundTimer->start(settings.value("settings/soundDelayTime").toInt()*1000);
        } else {
            TeaSound::instance()->enqueue();
        }
    }
}
